var scService = angular.module('scService', ["angular-popups"]);
scService.factory('commonService', function($q,$http,$httpParamSerializerJQLike) {
	var factory = {};
	factory.commonAjaxByGet = function(url) {
		var deferred = $q.defer();
		$http({
			  method: 'GET',
			  url: "/appserver" + url,
			  headers: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
			  }
		}).success(function(data, status, headers, config) { 
			deferred.resolve(data);
		}).error(function(data, status, headers, config) {});
		return deferred.promise;
	};
	factory.commonAjaxByPost = function(url, postData) {
		var deferred = $q.defer();
		$http({
			method: 'POST',
			data: $httpParamSerializerJQLike(postData),
			url: "/appserver" + url,
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
			},
			cache: false
		}).success(function(data, status, headers, config) {
			deferred.resolve(data);
		}).error(function(data,status,headers,config){
            deferred.reject(data);
        });
		return deferred.promise;
	};
	factory.commonAjaxByPut = function(url, postData) {
		var deferred = $q.defer();
		$http({
			method: 'PUT',
			data: $httpParamSerializerJQLike(postData),
			url: "/appserver" + url,
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
			},
			cache: false
		}).success(function(data, status, headers, config) {
			deferred.resolve(data);
		});
		return deferred.promise;
	};
	return factory;

});
scService.service('jsonToStr',function(){
    this.transform = function(jsonData){
        var string = '';
        
        for(str in jsonData){
            string = string + str +'=' + jsonData[str] +'&';
        }
        var _last = string.lastIndexOf('&');
        
        string = string.substring(0,_last);
        
        return string;
    };
});

// 接口方法
scService.service('scCodeService', function(commonService) {
	return {
		//发送验证码
		sendVerifyCode:function(postData){
			var url = "/pub/sendVerifyCode?phone="+postData.phone+"&merchantCode="+postData.merchantCode;
			return commonService.commonAjaxByGet(url);
		},
		//获取openId
		getOpenId:function(postData){
			 var url = "/pub/getAccessToken?source="+postData.source+"&merchantCode="+postData.merchantCode+"&code="+postData.code;
			return commonService.commonAjaxByGet(url);
		},
		// 获取userCard
		getUserCard:function(postData){
			var url = "/user/getUserCard?userId="+postData.userId;
			return commonService.commonAjaxByGet(url);
		},
		//登录（验证验证码）
		login:function(postData){
			var url = "/user/noLoginBindingUser";
			return commonService.commonAjaxByPost(url,postData);
		},
		//自动登录
		autoLogin:function(postData){
			var url = "/user/autoLogin";
			return commonService.commonAjaxByPost(url,postData);
		},
		//退出登录
		unlockUser:function(postData){
			var url = "/user/unlockUser";
			return commonService.commonAjaxByPost(url,postData);
		},
		//桩位详情
		getChargerListByStationId:function(stationId){
			var url = "/charger/getChargerListByStationId?stationId="+stationId;
			return commonService.commonAjaxByGet(url);
		},
		// 通过坐标获取城市名，id
		getCityNameAndCodeByCoordinate:function(postData){
			var url = "/pub/getCityNameAndCodeByCoordinate?latitude="+postData.latitude+"&longtitude="+postData.longtitude;
			return commonService.commonAjaxByGet(url);
		},
		//获取站点详情
		getStationDetail:function(postData){
			var url = "/station/getStationDetail?stationId="+postData.stationId+"&userId="+postData.userId;
			return commonService.commonAjaxByGet(url);
		},
		//获取站点标签
		getLables:function(postData){
			var url = "/pub/getLables?type="+postData.type+"&level="+postData.level;
			return commonService.commonAjaxByGet(url);
		},
		//查询充电桩详情
		getChargerDetailByQrCode: function(postData){
			var url = "/charger/getChargerDetailByQrCode?qrCode=" + postData.qrCode;
			return commonService.commonAjaxByGet(url);
		},
		//开启充电
		openCharge:function(postData){
			var url = "/charge/openCharge";
			return commonService.commonAjaxByPost(url,postData);
		},
		//结束充电
		closeCharge:function(postData){
			var url = "/charge/closeCharge";
			return commonService.commonAjaxByPut(url,postData);
		},
		//获取费率
		getRate:function(postData){
			var url = "/charger/getRate?chargerId="+postData.chargerId;
			return commonService.commonAjaxByGet(url);
		},
		//枪口充电实时状态
		getCurrentChargerInfo:function(postData){
			var url = "/getCurrentChargerInfo?qr_code="+postData.qrCode+"&plug_id="+postData.plugNo;
			return commonService.commonAjaxByGet(url);
		},
		//枪口状态
		plugStatus:function(postData){
			var url = "/charger/plugStatus?plugNo="+postData.plugNo+"&chargerId="+postData.chargerId;
			return commonService.commonAjaxByGet(url);
		},
		//获取正在进行的业务操作
		getOngoingOperation:function(postData){
			var url = "/charge/getOngoingOperation?userCard="+postData.userCard;
			return commonService.commonAjaxByGet(url);
		},
		//查询订单
		getOrderList:function(postData) {
			if(postData.status=="0"){
				var url = "/fund/getFundList?userId="+postData.userId+"&status="+postData.status+"&pageNo="+postData.pageNo;
			}else{
				var url = "/fund/getFundList?userId="+postData.userId+"&pageNo="+postData.pageNo;
			}
			
			return commonService.commonAjaxByGet(url);
		},
		//查询订单详细
		getOrderDetail:function(postData) {
			var url = "/fund/fundDetail?orderNo="+postData.orderNo;
			return commonService.commonAjaxByGet(url);
		},
		//获取支付参数
		getPayParams:function(postData) {
			var url = "/fund/generateOrders";
			return commonService.commonAjaxByPost(url,postData);
		},
		//調用微信签名
		getJsSign:function(postData){
			var url = "/pub/getJsSign?source="+mainConfig.source+"&merchantCode="+mainConfig.merchantCode+"&signType=sha1&url=" + window.location.href;
			return commonService.commonAjaxByGet(url);
		},
		//判断是否有支付订单
		getFundList:function(postData){
			var url = "/fund/getFundList?userId="+postData.userId+"&pageNo=1&status=0";
			return commonService.commonAjaxByGet(url);
		},
		//预约
		startReservation:function (postData) {
			var url = "/reservation/reservation";
			return commonService.commonAjaxByPost(url,postData);
		},
		//取消预约
		cancelReservation:function(postData) {
			var url = "/reservation/cancelReservation";
			return commonService.commonAjaxByPut(url,postData);
		},
		//获取城市列表
		getCityList:function(argument) {
			var url = "/manage/dic/CitySelect?provinceid=";
			return commonService.commonAjaxByGet(url);
		},
		//根据城市码搜索相关站点
		getStationByName:function(postData){
			var url = "/station/getStationByName?name=" + postData.stationName + "&latitude="+postData.latitude+"&longtitude="+postData.longtitude;
			return commonService.commonAjaxByGet(url);
		},
		getStationByCoordinate:function(postData){
			//alert(JSON.stringify(postData));
			var url ="/station/getStationByCoordinate?latitude="+postData.latitude+"&longtitude="+postData.longtitude+"&number="+postData.number+"&locaLatitude="+postData.locaLatitude+"&locaLongtitude="+postData.locaLongtitude;
			return commonService.commonAjaxByGet(url);
		},
		//订单附加信息（评分）
		 orderAttach:function(postData){
			var url ="/fund/orderAttach";
			return commonService.commonAjaxByPost(url,postData);
		},
		// 收藏(删除收藏)站点
		collectionStation:function(postData){
			var url ="/station/collectionStation";
			return commonService.commonAjaxByPost(url,postData);
		},
		// 获取收藏列表
		collectionStationList:function(postData){
			var url ="/station/collectionStationList?userId="+postData.userId+"&pageNo="+postData.pageNo;
			return commonService.commonAjaxByGet(url);
		},
        //评分
        scoreStation:function(postData){
            var url = "/fund/scoreStation";
            return commonService.commonAjaxByPost(url,postData);
        }
	};
});


// 公用方法
scService.factory('pubFun',  function($q,$http,scCodeService,Popup,$stateParams){
	var module = {};
	// 自动登录
	module.autoLogin=function() {
            // alert('自动登录执行了')
            var deferred = $q.defer();
            var openId = localStorage.getItem("openId")
            
            var postData = {
                "source": mainConfig.source,
                "merchantCode": mainConfig.merchantCode,
                "account": openId
                // "jPushRegId": openId
            }
            // alert(JSON.stringify(postData))
            scCodeService.autoLogin(postData).then(function(data) {
                // alert("自动登录提示："+JSON.stringify(data))
                if (data.code == "200") {
                    localStorage.setItem("isLogin", "true");
                    localStorage.setItem("userId", data.data.userId);
                    localStorage.setItem("token", data.data.token);
                    localStorage.setItem("phone", data.data.phone);
                    deferred.resolve()
                } else if (data.code == "0") {
                    Popup.notice('系统故障,请刷新页面', 2000);
                } else if (data.code == "201" || data.code == "0101001") {
                    // $scope.showLogin = true;
                    deferred.reject(data.code)
                } else {
                    Popup.notice('登录失败，请刷新页面', 2000);
                }
            });
            return deferred.promise;

        };
    //获取用户卡号
    module.getUserCard = function() {
        
        var deferred = $q.defer();
        var userId = localStorage.getItem("userId");
        var postData = {
            "userId": userId
        };
        /*$timeout(function() {
             deferred.resolve()
        }, 1000);*/
        scCodeService.getUserCard(postData).then(function(data) {
            var datastr = JSON.stringify(data);
            // alert(datastr);
            // $scope.loginIng = false; //登录成功关闭loading   
            if (data.code == "200") {
                localStorage.setItem("cardNo", data.data[0].cardNo)
                deferred.resolve()
            }

        });
        return deferred.promise;
    };
    // 查询有无未支付订单
    module.getPending = function() {
        var deferred = $q.defer();
        var userId = localStorage.getItem("userId");
        var postData = {
            userId: userId,
            pageNo: "1",
            status: "0"
        };
        scCodeService.getOrderList(postData).then(function(data) {
            var datastr = JSON.stringify(data);
            //alert(datastr);
            if (data.code == "200") {
                deferred.resolve(data.data)
            }else{
            }
        });
        return deferred.promise;
    };
    // 根据坐标查询站点
    module.getStationByCoordinate = function(data) {
        var postData = data;
        postData.number = "30";
        // $scope.stationsNum = "20";
        scCodeService.getStationByCoordinate(postData).then(function(data) {
            if (data.code == "200") {
                localStorage.setItem("searchResult",JSON.stringify(data.data));
            }
        });
    };
    // 查询有无未支付订单
    module.getPending = function() {
        var deferred = $q.defer();
        var userId = localStorage.getItem("userId");
        var postData = {
            userId: userId,
            pageNo: "1",
            status: "0"
        };
        scCodeService.getOrderList(postData).then(function(data) {
            var datastr = JSON.stringify(data);
            // alert("获取pending"+ datastr);
            if (data.code == "200") {
                deferred.resolve(data.data)
            }else{
            }
        });
        return deferred.promise;
    };
    // 获取正在进行中的业务 (全局)
    module.getOngoingOperation = function() {
        var deferred = $q.defer();
        var userCard = localStorage.getItem("cardNo");
        var postData = {
            userCard: userCard

        };
        scCodeService.getOngoingOperation(postData).then(function(data) {
            // alert(JSON.stringify(data));
            if (data.code == 200) {
                var processing = { chargeList: [], reservationList: [], hasOngoingOperation:true};
                if (globalFun.isEmptyObj(data.data) == false) {
                    angular.forEach(data.data.chargeList, function(value, index) {
                        if (value.status == "1") {
                            value.status = "正在充电";
                            value.type = "2";
                            processing.chargeList.push(value);
                        }
                    });
                    if(processing.chargeList=="" || processing.chargeList.length==0){
                        localStorage.setItem("openCharge","false");
                    }
                    angular.forEach(data.data.reservationList, function(value, index) {
                        if (value.status == "2") {
                            value.status = "预约成功";
                            value.type = "1";
                            processing.reservationList.push(value);
                        }
                    });
                } else {
                    localStorage.setItem("openCharge","false");
                    processing.hasOngoingOperation = false;
                }
                // alert("ongoing完成")
                deferred.resolve(processing);
            }else{
                localStorage.setItem("openCharge","false");
            }
        });
        return deferred.promise;
    };
    //获取站点详情
    module.getStationDetail = function(stationId) {
    	//alert("开始getStationDetail")
        var deferred = $q.defer();
        var userId = localStorage.getItem("userId");
        var postData = {
            userId: userId,
            stationId: stationId
        };
        // alert("开始getStationDetail postdata:"+JSON.stringify(postData))
        scCodeService.getStationDetail(postData).then(function(data) {
        	//alert(JSON.stringify(data))
            if (data.code == "200") {                
                data.data.score = data.data.grade*2;
                data.data.fScore = globalFun.decimal(data.data.grade,1)
                data.data.collectBtn = data.data.collectionFlag == "0" ? "收藏" : "取消";
                deferred.resolve(data.data)
            }
        })
        return deferred.promise;
    };
    // 获取城市名称
    module.getCityName = function(data){
    	// alert(JSON.stringify(data));
        var postData = data;
        scCodeService.getCityNameAndCodeByCoordinate(postData).then(function(data){
            if(data.code=="200"){
                var city = {
                    cityName:data.data.cityName,
                    cityId:data.data.cityId,
                    provinceName:data.data.provinceName
                };
                localStorage.setItem("city",JSON.stringify(city));
                // alert(JSON.stringify(city));
            };
        });
     };

     //获取预约费率
    module.getRate = function(chargerId) {
    	var deferred = $q.defer();
        var postData = {
            chargerId: chargerId
        }
        var mainRate = {};
        scCodeService.getRate(postData).then(function(data) {
            if (data.code == "200") {
                //费率处理
                for (var i = 0; i < data.data.length; i++) {
                    if (data.data[i].feeType == "3") {
                        mainRate.serveRate = data.data[i].rate;
                        mainRate.serveMode = data.data[i].chargeMode;
                        mainRate.serveModeStr= data.data[i].chargeMode=="0"?"度":"次";
                    } else if (data.data[i].feeType == "2") {
                        mainRate.chargerRate = data.data[i].rate;
                        mainRate.chargerMode = data.data[i].chargeMode;
                    } else if (data.data[i].feeType == "1") {
                        mainRate.reservationRate = data.data[i].rate;
                        mainRate.reservationMode = data.data[i].chargeMode;
                        mainRate.reservationModeStr = data.data[i].chargeMode=="0"?"分钟":"次";
                    }
                }
                deferred.resolve(mainRate);

            } else {
                Popup.notice('获取桩信息失败', 3000, function() {
                    
                });
            }
        });
        return deferred.promise;
    }

    //点击进入预约界面
    module.goToAppointing=function (qrCode,reservationSn) {
        var postData = {
            qrCode: qrCode
        }
        scCodeService.getChargerDetailByQrCode(postData).then(function(data) {
            
            if (data.code == "200") {
                if (data.data) {
                     var chargerDetail = data.data;
                    //组装桩类型数据
                    if (chargerDetail.chargerType == "1") {
                        chargerDetailType = "直流 快充"
                    } else if (chargerDetail.chargerType == "2") {
                        chargerDetailType = "交流220V 慢充"
                    }
                    module.getRate(chargerDetail.chargerId).then(function(data){
                        var mainRate = data;
                        localStorage.setItem("chargerDetail", JSON.stringify(chargerDetail));
                        localStorage.setItem("mainRate", JSON.stringify(mainRate));
                        module.getStationDetail(chargerDetail.stationId).then(function (data) {
                            localStorage.setItem("latitude",data.latitude);
                            localStorage.setItem("longitude",data.longitude);
                            window.location.href = mainConfig.hostUrl+'index.html#/appointing/'+reservationSn;
                        });
                    });
                }

            } else {
                Popup.notice('获取桩信息失败', 3000);
            }
        })
    }
    //点击进入充电界面
    module.goToCharging=function (qrCode,chargeSn,startTime,startTimestr) {
        var postData = {
            qrCode: qrCode
        }
        scCodeService.getChargerDetailByQrCode(postData).then(function(data) {
            
            if (data.code == "200") {
                if (data.data) {
                    var chargerDetail = data.data;
                    var temp = new Date();
                    var SMS = Date.parse(temp);
                    localStorage.setItem("SMS", startTime);
                    
                    localStorage.setItem("startTime", startTimestr);
                    //判断充电开启状态
                    var openCharge = "true";
                    localStorage.setItem("openCharge", openCharge);
                    localStorage.setItem("chargerDetail", JSON.stringify(chargerDetail));
                    //chargerId and plugNo
                    localStorage.setItem("chargerId", chargerDetail.chargerId);
                    localStorage.setItem("plugNo", chargerDetail.plugNoList[0].portNo);
                    module.getRate(chargerDetail.chargerId).then(function(data){
                        localStorage.setItem("rate", data.chargerRate);
                        window.location.href = mainConfig.hostUrl+'index.html#/charging/'+chargeSn;
                    });
                    
                }
            } else {
                Popup.notice('获取桩信息失败', 3000, function() {
                    
                });
            }
        })
        
    };
    return module;
})

